// =================================
// DOM 和状态初始化
// =================================
const commandInput = document.getElementById('command-input');
const executeBtn = document.getElementById('execute-btn');
const chatMessages = document.getElementById('chat-messages');
const statusMessage = document.getElementById('status-message');
const connectionStatus = document.getElementById('connection-status');
const sessionSidebar = document.getElementById('session-sidebar');
const menuToggleBtn = document.getElementById('menu-toggle-btn');
const newChatBtn = document.getElementById('new-chat-btn');
const sessionList = document.getElementById('session-list');
const overlay = document.getElementById('overlay');

// 后端API地址 - 现在通过declarativeNetRequest重定向
// const API_BASE_URL = 'https://api.ecom-pilot.ai';
let conversations = {};
let currentSessionId = null;
let pageInfo = {};
let isLoading = false;
let currentAssistantMessageElement = null;

// =================================
// 初始化
// =================================
document.addEventListener('DOMContentLoaded', async () => {
    await loadStateFromStorage();
    
    // 设置事件监听器
  executeBtn.addEventListener('click', handleUserInput);
  commandInput.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleUserInput();
    }
  });
    menuToggleBtn.addEventListener('click', toggleSessionSidebar);
    overlay.addEventListener('click', toggleSessionSidebar);
    newChatBtn.addEventListener('click', createNewSession);

    // 设置后台监听器
  chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
        if (changeInfo.status === 'complete') getCurrentTabInfo();
    });
    chrome.tabs.onActivated.addListener(getCurrentTabInfo);

    // 设置消息监听器，处理来自background.js的消息
    chrome.runtime.onMessage.addListener(handleBackgroundMessages);
    
    checkBackendStatus();
    setInterval(checkBackendStatus, 15000);
    getCurrentTabInfo();
});

// =================================
// 状态与存储管理
// =================================
async function loadStateFromStorage() {
    const data = await chrome.storage.local.get(['conversations', 'currentSessionId']);
    conversations = data.conversations || {};
    currentSessionId = data.currentSessionId || null;

    if (!currentSessionId || !conversations[currentSessionId]) {
        createNewSession();
    } else {
        renderCurrentSession();
        renderSessionList();
    }
}

async function saveStateToStorage() {
    await chrome.storage.local.set({ conversations, currentSessionId });
}

// =================================
// 会话管理
// =================================
function createNewSession() {
    const newSessionId = `session_${Date.now()}`;
    conversations[newSessionId] = [];
    currentSessionId = newSessionId;
    
    renderCurrentSession();
    renderSessionList();
    saveStateToStorage();
    
    sessionSidebar.classList.remove('open');
    overlay.classList.remove('visible');
    console.log(`Created and switched to new session: ${newSessionId}`);
}

function switchSession(sessionId) {
    if (sessionId === currentSessionId) return;
    currentSessionId = sessionId;
    
    renderCurrentSession();
    renderSessionList(); // 更新 'active' 类
    saveStateToStorage();
    
    sessionSidebar.classList.remove('open');
    overlay.classList.remove('visible');
    console.log(`已切换到会话: ${sessionId}`);
    console.log('会话历史:', conversations[sessionId]);
}

function deleteSession(sessionId) {
    if (Object.keys(conversations).length <= 1) {
        alert("不能删除最后一个会话！");
        return;
    }
    
    delete conversations[sessionId];

    if (currentSessionId === sessionId) {
        // 切换到最近的会话
        currentSessionId = Object.keys(conversations).sort().pop();
    }
    
    renderCurrentSession();
    renderSessionList();
    saveStateToStorage();
    console.log(`Deleted session: ${sessionId}`);
}

function toggleSessionSidebar() {
    sessionSidebar.classList.toggle('open');
    overlay.classList.toggle('visible');
}

// =================================
// 渲染函数
// =================================
function renderCurrentSession() {
    chatMessages.innerHTML = '';
    const messages = conversations[currentSessionId] || [];
    if (messages.length === 0) {
        const welcomeMessage = document.createElement('div');
        welcomeMessage.className = 'welcome-message';
        welcomeMessage.innerHTML = `<p>我可以帮助您管理电商后台，请问有什么可以帮您？</p><p>例如: <strong>将'夏日凉鞋'价格改为199元</strong></p>`;
        chatMessages.appendChild(welcomeMessage);
    } else {
        messages.forEach(msg => addMessageToDOM(msg.role, msg.content));
    }
}

function renderSessionList() {
    sessionList.innerHTML = '';
    Object.keys(conversations).sort().reverse().forEach(sessionId => {
        const sessionItem = document.createElement('div');
        sessionItem.className = 'session-item';
        if (sessionId === currentSessionId) {
            sessionItem.classList.add('active');
        }
        sessionItem.dataset.sessionId = sessionId;
        
        const firstUserMessage = conversations[sessionId].find(m => m.role === 'user');
        const title = firstUserMessage ? firstUserMessage.content : "新会话";
        
        const titleSpan = document.createElement('span');
        titleSpan.textContent = title;
        sessionItem.appendChild(titleSpan);

        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-session-btn';
        deleteBtn.innerHTML = '×';
        deleteBtn.onclick = (e) => {
            e.stopPropagation();
            deleteSession(sessionId);
        };
        sessionItem.appendChild(deleteBtn);
        
        sessionItem.onclick = () => switchSession(sessionId);
        
        sessionList.appendChild(sessionItem);
    });
}

// =================================
// 核心聊天逻辑
// =================================
async function handleUserInput() {
    const userInput = commandInput.value.trim();
    if (!userInput || isLoading) return;

    setLoading(true);
    commandInput.value = '';

    const userMessage = { role: 'user', content: userInput };
    conversations[currentSessionId].push(userMessage);
    addMessageToDOM(userMessage.role, userMessage.content);
    
    await saveStateToStorage();
    renderSessionList(); // 如果是第一条消息，则更新会话标题
    
    try {
        // 添加一个空的助手消息，并保存对其的引用
        currentAssistantMessageElement = addMessageToDOM('assistant', '');
        
        // 通过background.js发送消息到后端
        chrome.runtime.sendMessage({
            action: 'send_chat_message',
            data: {
                messages: conversations[currentSessionId],
                session_id: currentSessionId
            }
        }, response => {
            if (!response || !response.success) {
                console.error('发送消息失败:', response);
                addMessageToDOM('assistant', `发送消息失败: ${response?.message || '未知错误'}`);
                setLoading(false);
            }
        });
        
        // 注意：我们不再在这里等待响应，而是通过消息监听器接收流式响应
        
    } catch (error) {
        console.error('Error in sendMessage:', error);
        addMessageToDOM('assistant', `错误: ${error.message}`);
        setLoading(false);
    }
}

function addMessageToDOM(role, content) {
    const welcomeMessage = document.querySelector('.welcome-message');
    if (welcomeMessage) welcomeMessage.style.display = 'none';

    if (role === 'tool') {
        const toolCard = createToolCard(content);
        chatMessages.appendChild(toolCard);
        chatMessages.scrollTop = chatMessages.scrollHeight;
        return;
    }

    const wrapper = document.createElement('div');
    wrapper.classList.add('message-wrapper', `${role}-wrapper`);

    const messageElement = document.createElement('div');
    messageElement.classList.add('chat-message', `${role}-message`);
    
    // 如果是助手消息，并且内容为空，表示这是一个等待流式更新的消息
    if (role === 'assistant' && !content) {
        messageElement.innerHTML = '<span class="typing-indicator">...</span>';
    } else {
        messageElement.innerHTML = content.replace(/\n/g, '<br>');
    }

    wrapper.appendChild(messageElement);
    chatMessages.appendChild(wrapper);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    
    return messageElement;
}

function setLoading(loading) {
    isLoading = loading;
    commandInput.disabled = loading;
    executeBtn.disabled = loading;
    statusMessage.textContent = loading ? '' : '';
    if (!loading) {
        commandInput.value = '';
        commandInput.focus();
    }
}

// 处理来自background.js的消息
function handleBackgroundMessages(message) {
    console.log('侧边栏收到消息:', message);
    
    if (message.type === 'chat_response') {
        // 当收到AI的正式回复时，移除所有临时的状态指示器
        const autoStatusElement = document.getElementById('auto-execution-status');
        if (autoStatusElement) {
            autoStatusElement.remove();
        }

        // 检查我们是否有一个正在等待更新的助手消息元素
        if (currentAssistantMessageElement) {
            // 检查这是否是该消息的第一块内容
            const isFirstChunk = currentAssistantMessageElement.innerHTML.includes('...');

            if (isFirstChunk) {
                currentAssistantMessageElement.innerHTML = message.content;
            } else {
                currentAssistantMessageElement.innerHTML += message.content;
            }
            
            // 每次收到消息块时保存当前状态，确保即使没有收到 conversation_end 也能保存回复
            const currentContent = currentAssistantMessageElement.innerHTML.replace(/<br>/g, '\n');
            // 检查是否已经有助手消息
            const lastMessage = conversations[currentSessionId][conversations[currentSessionId].length - 1];
            if (lastMessage && lastMessage.role === 'assistant') {
                // 更新现有的助手消息
                lastMessage.content = currentContent;
            } else {
                // 添加新的助手消息
                conversations[currentSessionId].push({ role: 'assistant', content: currentContent });
            }
            saveStateToStorage();
            
            chatMessages.scrollTop = chatMessages.scrollHeight;
        } else {
             console.warn('收到聊天响应，但没有找到当前助手的消息元素来更新。');
        }
    } else if (message.type === 'error') {
        console.error('收到错误消息:', message.content);
        if(currentAssistantMessageElement) {
            currentAssistantMessageElement.innerHTML = `错误: ${message.content}`;
            currentAssistantMessageElement.classList.add('error-message');
        } else {
        addMessageToDOM('assistant', `错误: ${message.content}`);
        }
        setLoading(false);
    } else if (message.type === 'tool_executed') {
        console.log('工具执行:', message.command);
        // 可以在这里添加一个提示，告诉用户工具已被执行
        const toolMsg = document.createElement('div');
        toolMsg.className = 'tool-execution-message';
        toolMsg.innerHTML = `<small>执行了操作: ${message.command.action}</small>`;
        chatMessages.appendChild(toolMsg);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    } else if (message.type === 'tool_auto_execution_started') {
        console.log('工具自动执行开始:', message.payload);
        renderAutoExecutionStatus(message.payload);
    } else if (message.type === 'conversation_end') {
        console.log('收到对话结束信号，保存对话');
        finalizeAssistantMessage();
    } else if (message.type === 'tool_approval_request') {
        console.log('收到工具批准请求:', message.payload);
        renderApprovalCard(message.payload.tool_calls);
        setLoading(false); // 允许用户与批准卡片交互
    } else if (message.type === 'tool_result_reported') {
        console.log('收到工具执行汇报:', message.data);
        // 将工具执行结果保存到对话历史中
        const toolMessage = { role: 'tool', content: JSON.stringify(message.data) };
        conversations[currentSessionId].push(toolMessage);
        saveStateToStorage();
        // 显示工具执行结果卡片
        addMessageToDOM('tool', message.data);
    }
    
    setLoading(false);
}

function renderAutoExecutionStatus(payload) {
    // 移除任何已存在的旧状态，确保只有一个状态指示器
    const existingStatus = document.getElementById('auto-execution-status');
    if (existingStatus) {
        existingStatus.remove();
    }

    const card = document.createElement('div');
    card.id = 'auto-execution-status'; // 使用ID方便查找和删除
    card.className = 'tool-auto-execution-message'; // 复用现有样式

    let descriptions = [];
    for (const call of payload.tool_calls) {
        const toolName = call.name;
        const toolArgs = call.args;

        if (toolName === 'click') {
            descriptions.push(`点击元素: ${toolArgs.selector}`);
        } else if (toolName === 'navigate_to_url') {
            descriptions.push(`导航到: ${toolArgs.url}`);
        } else {
            descriptions.push(`执行工具: ${toolName}`);
        }
    }

    card.innerHTML = `<small>AI助手正在自动: ${descriptions.join(', ')}</small>`;
    chatMessages.appendChild(card);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 添加一个函数，在所有消息接收完成后保存对话
function finalizeAssistantMessage() {
    if (!isLoading) return;
    
    // 从DOM中获取最终的、完整的消息内容
    if (currentAssistantMessageElement) {
        const fullContent = currentAssistantMessageElement.innerHTML.replace(/<br>/g, '\n');
        
        // 检查是否已经有助手消息
        const lastMessage = conversations[currentSessionId][conversations[currentSessionId].length - 1];
        if (lastMessage && lastMessage.role === 'assistant') {
            // 更新现有的助手消息
            lastMessage.content = fullContent;
        } else {
            // 添加新的助手消息
            conversations[currentSessionId].push({ role: 'assistant', content: fullContent });
        }
        
        saveStateToStorage();
        console.log('对话已完成并保存，当前历史:', conversations[currentSessionId]);
    }
    
    setLoading(false);
    currentAssistantMessageElement = null; // 清空引用
}

function renderApprovalCard(toolCalls) {
    const card = document.createElement('div');
    card.className = 'approval-card';

    let content = '<h5>AI 助手请求执行以下操作：</h5><ul>';

    const translations = {
        navigate_to_url: (args) => `网页导航：即将打开 <a href="${args.url}" target="_blank" title="在新标签页中打开链接">${args.url}</a>`
        // 在这里可以为其他工具添加翻译
        // 'update_product_price': (args) => `更新价格：将商品'${args.product_name}'的价格修改为 ${args.new_price}元`
    };

    toolCalls.forEach(call => {
        const translationFunc = translations[call.name];
        const description = translationFunc ? translationFunc(call.args) : `执行工具: <strong>${call.name}</strong>，参数: <code>${JSON.stringify(call.args)}</code>`;
        content += `<li>${description}</li>`;
    });

    content += '</ul><p>您要批准吗？</p>';
    card.innerHTML = content;

    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'approval-buttons';

    const approveBtn = document.createElement('button');
    approveBtn.textContent = '批准';
    approveBtn.className = 'approve-btn';
    approveBtn.onclick = () => handleApproval(toolCalls, card);

    const rejectBtn = document.createElement('button');
    rejectBtn.textContent = '拒绝';
    rejectBtn.className = 'reject-btn';
    rejectBtn.onclick = () => handleRejection(toolCalls, card);

    buttonContainer.appendChild(approveBtn);
    buttonContainer.appendChild(rejectBtn);
    card.appendChild(buttonContainer);

    chatMessages.appendChild(card);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

async function handleApproval(toolCalls, card) {
    card.remove();

    const statusDiv = document.createElement('div');
    statusDiv.className = 'tool-execution-message';
    statusDiv.innerHTML = `<small>正在执行操作...</small>`;
    chatMessages.appendChild(statusDiv);

    try {
        const toolOutputs = [];
        // 注意：这里我们不再并行执行，因为某些操作（如导航）会相互影响
        for (const call of toolCalls) {
            console.log(`请求在背景页执行工具: ${call.name}`);
            const response = await chrome.runtime.sendMessage({
                action: 'execute_tool',
                tool_name: call.name,
                tool_args: call.args
            });

            if (response && response.success) {
                console.log(`工具 ${call.name} 执行成功`, response.output);
                toolOutputs.push({
                    tool_call_id: call.id,
                    output: JSON.stringify(response.output)
                });
            } else {
                console.error(`工具 ${call.name} 执行失败:`, response.error);
                toolOutputs.push({
                    tool_call_id: call.id,
                    output: JSON.stringify({ error: `执行失败: ${response.error}` })
                });
                // 如果一个工具失败，可能需要停止后续工具的执行
                break; 
            }
        }
        
        statusDiv.remove(); // 移除"正在执行"的提示
        setLoading(true);   // 在等待AI回复时显示加载状态
        resumeChat(toolOutputs);

    } catch (error) {
        console.error('执行工具时出错:', error);
        statusDiv.remove();
        addMessageToDOM('assistant', `执行工具时出错: ${error.message}`);
        setLoading(false); // 出错时停止加载
    }
}

async function handleRejection(toolCalls, card) {
    console.log("用户拒绝了工具执行");
    card.remove(); // 移除批准卡片

    const toolOutputs = toolCalls.map(call => ({
        tool_call_id: call.id,
        output: JSON.stringify({ error: "操作被用户拒绝。" })
    }));
    
    // 告知后端用户已拒绝
    resumeChat(toolOutputs);
}

async function resumeChat(toolOutputs) {
    try {
        await chrome.runtime.sendMessage({
            action: 'resume_chat_stream',
            data: {
                session_id: currentSessionId,
                tool_outputs: toolOutputs
            }
        });
        
        // 确保在工具执行后创建新的助手消息元素，以便接收后续回复
        if (!currentAssistantMessageElement) {
            currentAssistantMessageElement = addMessageToDOM('assistant', '');
        }
        
        // 响应将通过 handleBackgroundMessages 流式处理
        // 此处不再设置 setLoading(false)，等待 conversation_end 或下一次批准请求
    } catch (error) {
        console.error('恢复聊天时出错:', error);
        addMessageToDOM('assistant', `错误: ${error.message}`);
        setLoading(false); // 只有在出错时才停止加载
    }
}

async function checkBackendStatus() {
    try {
        const response = await fetch('https://api.ecom-pilot.ai/api/health');
        if (response.ok) {
            connectionStatus.textContent = '在线';
            connectionStatus.className = 'status-online';
        } else {
            connectionStatus.textContent = '离线';
            connectionStatus.className = 'status-offline';
        }
    } catch (error) {
        connectionStatus.textContent = '离线';
        connectionStatus.className = 'status-offline';
    }
}

function getCurrentTabInfo() {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]) {
            pageInfo = {
                url: tabs[0].url,
                title: tabs[0].title
            };
            console.log("获取当前标签页信息:", pageInfo);
        } else {
            console.log("无法获取当前标签页信息。");
        }
    });
}

function createToolCard(data) {
    const card = document.createElement('div');
    card.className = 'tool-card';

    // 如果数据是字符串（JSON格式），尝试解析它
    let toolData = data;
    if (typeof data === 'string') {
        try {
            toolData = JSON.parse(data);
        } catch (e) {
            console.error('无法解析工具数据:', e);
        }
    }

    // 提取工具名称、参数和结果
    const { name, args, result } = toolData || {};
    const success = result && result.success;

    // 格式化参数和结果以便显示
    const formattedArgs = args ? JSON.stringify(args, null, 2) : '{}';
    const formattedResult = result ? JSON.stringify(result, null, 2) : '{}';

    card.innerHTML = `
        <div class="tool-card-header ${success ? 'success' : 'failure'}">
            <svg class="tool-icon" viewBox="0 0 24 24"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>
            <strong>工具执行: ${name || '未知工具'}</strong>
            <span class="status-badge">${success ? '成功' : '失败'}</span>
        </div>
        <div class="tool-card-body">
            <details>
                <summary>查看详情</summary>
                <div class="tool-details">
                    <p><strong>参数:</strong></p>
                    <pre>${formattedArgs}</pre>
                    <p><strong>结果:</strong></p>
                    <pre>${formattedResult}</pre>
                </div>
            </details>
        </div>
    `;

    // 默认折叠
    card.querySelector('details').open = false;

    return card;
}